package com.zmx.patientend.view.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.patientend.BaseActivity;
import com.zmx.patientend.R;
import com.zmx.patientend.adapter.PatientMessageAdapter;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.pojo.Patient;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 时间：2020/4/30 17:10
 * 功能：患者信息
 */
public class PatientMessageActivity extends BaseActivity {

    @BindView(R.id.add)
    Button add;
    @BindView(R.id.reView)
    RecyclerView reView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private List<Patient> list;
    private PatientMessageAdapter adapter;
    private View mEmptyLayout;

    private Integer logo;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_patient_message;
    }

    @Override
    protected void initViews() {


        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);

        logo = this.getIntent().getIntExtra("logo",0);

        mEmptyLayout = findViewById(R.id.empty);
        list = new ArrayList<>();
        reView = findViewById(R.id.reView);
        reView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new PatientMessageAdapter(mActivity);
        reView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                //目前Activity→目标Activity
                if (logo == 1){

                    Intent intent = new Intent(mActivity,PatientMessageDetailsActivity.class);
                    intent.putExtra("patient_id",list.get(listPosition).getPatient_id());
                    startActivity(intent);

                }else{

                    Intent intent =getIntent();
                    Bundle bundle =new Bundle();
                    bundle.putString("patient_id",list.get(listPosition).getPatient_id());//回发的消息
                    intent.putExtras(bundle);
                    setResult(RESULT_OK,intent);
                    finish();

                }


            }
        });

        // 开启自动加载功能
        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setOnRefreshListener(refreshLayout -> {

            getData();

        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> {

            handler.sendEmptyMessage(3);

        });

        //触发自动刷新
        refreshLayout.autoRefresh();
    }

    private AlertDialog alertDialog1; //信息框
    int relation = 0;

    @OnClick(R.id.add)
    public void onViewClicked() {


        final String[] items = {"本人", "父母", "妻子", "儿女", "其他"};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle("选择与患者关系");
        alertBuilder.setItems(items, (dialogInterface, i) -> {
//                Toast.makeText(MainActivity.this, items[i], Toast.LENGTH_SHORT).show();

            if (items[i].equals("本人")) {

                relation = 4;

            } else if (items[i].equals("父母")) {

                relation = 1;

            } else if (items[i].equals("妻子")) {

                relation = 2;

            } else if (items[i].equals("儿女")) {

                relation = 3;

            } else {
                relation = 5;
            }

            Bundle bundle = new Bundle();
            bundle.putString("relation", relation+"");
            startActivity(AddPatientActivity.class,bundle);
            alertDialog1.dismiss();
        });
        alertDialog1 = alertBuilder.create();
        alertDialog1.show();


    }

    @Override
    protected void onRestart() {
        super.onRestart();

        //触发自动刷新
        refreshLayout.autoRefresh();
    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:
                    Log.e("数据", "数据" + msg.obj);
                    list.clear();
                    try {

                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        if (jsonObject.getInt("code") == 1) {
                            JSONArray array = jsonObject.getJSONArray("data");
                            Gson g = new Gson();
                            for (int i = 0; i < array.length(); i++) {

                                JSONObject object = array.getJSONObject(i);
                                Patient p = g.fromJson(object.toString(), Patient.class);
                                list.add(p);

                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    adapter.setListAndNotifyDataSetChanged(list);
                    handler.sendEmptyMessage(2);

                    break;

                case 2:

                    //刷新加载
                    refreshLayout.finishRefresh(true);
                    if (list.size() > 0) {

                        mEmptyLayout.setVisibility(View.GONE);

                    } else {

                        mEmptyLayout.setVisibility(View.VISIBLE);

                    }
                    break;
                case 3:
                    refreshLayout.finishLoadMore(true);
                    break;

            }

        }
    };


    /**
     * 获取所有患者信息
     */
    public void getData() {

        List<String> ls = new ArrayList<>();
        ls.add("0");

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "patientList");
        params.put("data[patient_id]", "0");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 1, 404);

    }

}
